<template>
  <div :class="classes">
    <slot name="prepend"></slot>
    <textarea v-if="$attrs.type=='textarea'" v-bind="props" v-on="listeners"/>
    <input v-else v-bind="props" v-on="listeners"/>
    <slot name="append"></slot>
    <span v-if="numberWord" class="m-input-word-counter">{{value.length}}/{{$attrs.maxlength}}</span>
  </div>
</template>

<script>
export default {
  componentName: 'MInput',
  props: {
    value: [String, Number],
    numberWord: Boolean,
    disabled: Boolean
  },
  data () {
    return {
      focus: false
    }
  },
  computed: {
    listeners () {
      return {
        ...this.$listeners,
        focus: this.handleFocus,
        blur: this.handleBlur,
        input: this.handleInput
      }
    },
    props () {
      return {
        type: 'text',
        ...this.$props,
        ...this.$attrs
      }
    },
    classes () {
      let result = ['m-input']
      if (this.focus) {
        result.push('m-input--focus')
      }
      if (this.$slots.prepend) {
        result.push('m-input--prepend')
      }
      if (this.$slots.append) {
        result.push('m-input--append')
      }
      if (this.numberWord && this.$attrs.maxlength) {
        result.push('m-input--number-word')
      }
      if (this.$attrs.type === 'textarea') {
        result.push('m-input--textarea')
      }
      return result
    }
  },
  methods: {
    handleFocus (e) {
      this.focus = true
      this.$emit('focus', e)
    },
    handleBlur (e) {
      this.focus = false
      this.$emit('blur', e)
    },
    handleInput (e) {
      this.$emit('input', e.target.value).$emit('change', e.target.value)
    }
  }
}
</script>

<style lang="scss">
  .m-input{
    text-align:left;
    position:relative;
    height:0.9rem;
    input,textarea{
      @include input;
      height:100%;
      resize: none;
    }
    textarea{
      padding:10px 0;
    }
    &:before{
      @include divider($color-divider);
      content: "";
      display: block;
      height: 1px;
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      z-index: 1;
    }
    &--focus:before{
      @include divider($color-primary);
    }
    &--prepend,&--append{
      display: flex;
      align-items: center
    }
    &--number-word{
      textarea{
        padding-bottom:20px;
      }
    }
    &-word-counter{
      position: absolute;
      right: 1px;
      margin-top: -10px;
      background: #fff;
      top: 50%;
      padding: 0 5px;
      text-align: right;
      box-sizing: border-box;
      border: 1px solid transparent;
      border-bottom-left-radius: 3px;
      border-bottom-right-radius: 3px;
      line-height: 20px;
      font-size:12px;
      color:$color-sub;
    }
    &--textarea{
      height: 1.5rem;
      .m-input-word-counter{
        top:auto;
        bottom:0;
      }
    }
  }
</style>
